package com.alibaba.sample.kantiezi.biz.user.ao;

import com.alibaba.biz.command.ao.ApplicationObjectSupport;
import com.alibaba.biz.command.result.Result;
import com.alibaba.biz.command.result.ResultSupport;

import com.alibaba.common.lang.StringUtil;

import com.alibaba.sample.kantiezi.dal.dataobject.User;
import com.alibaba.sample.kantiezi.biz.user.ao.result.RegisterResultCode;
import com.alibaba.sample.kantiezi.biz.user.manager.DuplicatedUserException;
import com.alibaba.sample.kantiezi.biz.user.manager.UserManager;

public class Register extends ApplicationObjectSupport {
    private UserManager userManager;
    private User        user;

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void afterPropertiesSet() throws Exception {
        if (user == null) {
            throw new IllegalArgumentException("missing user");
        }

        if (StringUtil.isEmpty(user.getUserId())) {
            throw new IllegalArgumentException("missing user.userId");
        }

        if ("register".equals(getEvent()) && StringUtil.isEmpty(user.getPassword())) {
            throw new IllegalArgumentException("missing user.password");
        }
    }

    public Result doRegisterBasic() {
        Result result = new ResultSupport();

        try {
            userManager.register(user);
        } catch (DuplicatedUserException e) {
            result.setSuccess(false);
            result.setResultCode(RegisterResultCode.DUPLICATED_USER_ID);
        }

        return result;
    }

    public Result doRegisterAccount() {
        Result result = new ResultSupport();

        userManager.registerAccount(user);

        return result;
    }
}
